<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
 
// import Joomla controllerform library
jimport('joomla.application.component.controllerform');
 
/**
 * Product Controller
 */
class ProductControllerCart extends JControllerForm
{
	public function add() {
		$session =& JFactory::getSession();
		$cart = $session->get("cart");
		if (!isset($cart) || !is_array($cart)) {
			$cart = array();
		}
	
		$id = JRequest::getInt("id");
		$qty = JRequest::getInt("qty");
		$this->correctQty($qty);
	
		$isNew = true;
		foreach ($cart as &$item) {
			if ($item['id'] == $id) {
				$item['qty'] = $item['qty'] + $qty;
				$isNew = false;
				break;
			}
		}
		if ($isNew) {
			$new = array('id' => $id, 'qty' => $qty);
			array_push($cart, $new);
		}
		$session->set("cart", $cart);

		$this->setRedirect('index.php?option=com_product&view=cart');
		return true;
	}
	
	public function update() {
		$session =& JFactory::getSession();
		$cart = $session->get("cart");
		if (isset($cart) && is_array($cart)) {
			foreach ($cart as &$item) {
				$qty = JRequest::getInt('qty_' . $item['id']);
				if (isset($qty)) {
					$this->correctQty($qty);
					$item['qty'] = $qty;
				}
			}
			
			$session->set("cart", $cart);
		}
		
		$this->setRedirect('index.php?option=com_product&view=cart');
		return true;
	}
	
	public function delete() {
		$session =& JFactory::getSession();
		$cart = $session->get("cart");
		$id = JRequest::getInt('id');
		echo $id;
		if (isset($cart) && is_array($cart) && isset($id)) {
			foreach ($cart as $i => $item) {
				if ($item['id'] == $id) {
					unset($cart[$i]);
					break;
				}
			}
			$session->set("cart", $cart);
		}
		$this->setRedirect('index.php?option=com_product&view=cart');
		return true;
	}
		
	private function correctQty(&$qty) {
		if ($qty < 1)  $qty = 1;
		if ($qty > 99) $qty = 99;
	}
}